#!/usr/bin/env python3
"""
DSL字段优化脚本 - 优化重复的字段定义
主要优化内容：
1. 标准化通用字段 (id, createdAt, updatedAt)
2. 简化冗余的description字段
3. 统一字段格式和规则
"""

import os
import re
import yaml
import sys
from pathlib import Path
from collections import defaultdict

def load_yaml_file(file_path):
    """加载YAML文件"""
    try:
        with open(file_path, 'r', encoding='utf-8') as f:
            return yaml.safe_load(f)
    except Exception as e:
        print(f"❌ 无法加载文件 {file_path}: {e}")
        return None

def save_yaml_file(file_path, data):
    """保存YAML文件"""
    try:
        with open(file_path, 'w', encoding='utf-8') as f:
            yaml.dump(data, f, default_flow_style=False, allow_unicode=True, sort_keys=False)
        return True
    except Exception as e:
        print(f"❌ 无法保存文件 {file_path}: {e}")
        return False

def analyze_common_fields(all_entities):
    """分析所有实体中的通用字段"""
    field_stats = defaultdict(lambda: {'count': 0, 'definitions': []})
    
    for file_name, entities in all_entities.items():
        for entity_name, entity_def in entities.items():
            if 'attributes' in entity_def:
                for field_name, field_def in entity_def['attributes'].items():
                    field_stats[field_name]['count'] += 1
                    field_stats[field_name]['definitions'].append({
                        'file': file_name,
                        'entity': entity_name,
                        'definition': field_def
                    })
    
    return field_stats

def get_standard_field_definition(field_name, definitions):
    """获取字段的标准定义"""
    standard_definitions = {
        'id': {
            'type': 'uuid',
            'rules': ['required'],
            'description': '唯一标识'
        },
        'createdAt': {
            'type': 'datetime',
            'rules': ['required'],
            'description': '创建时间'
        },
        'updatedAt': {
            'type': 'datetime',
            'rules': [],
            'description': '更新时间'
        }
    }
    
    if field_name in standard_definitions:
        return standard_definitions[field_name]
    
    # 对于其他字段，尝试从现有定义中找到最佳的
    if definitions:
        # 选择最完整的定义作为标准
        best_def = max(definitions, key=lambda d: len(d['definition']))
        return best_def['definition']
    
    return None

def optimize_field_definitions(entities, field_stats):
    """优化字段定义"""
    changes = []
    
    # 定义需要标准化的通用字段
    common_fields = ['id', 'createdAt', 'updatedAt']
    
    for entity_name, entity_def in entities.items():
        if 'attributes' not in entity_def:
            continue
            
        attributes = entity_def['attributes']
        
        for field_name in common_fields:
            if field_name in attributes:
                current_def = attributes[field_name]
                standard_def = get_standard_field_definition(field_name, 
                    field_stats[field_name]['definitions'])
                
                if standard_def:
                    # 检查是否需要更新
                    needs_update = False
                    updates = {}
                    
                    # 检查类型
                    if current_def.get('type') != standard_def.get('type'):
                        updates['type'] = standard_def['type']
                        needs_update = True
                    
                    # 检查规则
                    current_rules = current_def.get('rules', [])
                    standard_rules = standard_def.get('rules', [])
                    if current_rules != standard_rules:
                        updates['rules'] = standard_rules
                        needs_update = True
                    
                    # 检查描述
                    current_desc = current_def.get('description', '')
                    standard_desc = standard_def.get('description', '')
                    if not current_desc and standard_desc:
                        updates['description'] = standard_desc
                        needs_update = True
                    elif current_desc != standard_desc and len(current_desc) < 5:
                        updates['description'] = standard_desc
                        needs_update = True
                    
                    if needs_update:
                        attributes[field_name].update(updates)
                        changes.append(f"    🔧 标准化字段 '{field_name}': {entity_name}")
    
    return changes

def simplify_descriptions(attributes):
    """简化冗余的description字段"""
    changes = []
    
    # 定义可以简化的描述模式
    simplification_rules = {
        r'^用户唯一标识$': '用户ID',
        r'^系统唯一标识$': '系统ID',
        r'^.*的唯一标识$': 'ID',
        r'^记录创建时间$': '创建时间',
        r'^记录更新时间$': '更新时间',
        r'^最后更新时间$': '更新时间',
        r'^数据创建时间$': '创建时间',
        r'^数据更新时间$': '更新时间',
    }
    
    for attr_name, attr_def in attributes.items():
        if 'description' in attr_def:
            desc = attr_def['description']
            
            for pattern, replacement in simplification_rules.items():
                if re.match(pattern, desc):
                    if desc != replacement:
                        attr_def['description'] = replacement
                        changes.append(f"    📝 简化描述 '{attr_name}': '{desc}' -> '{replacement}'")
                    break
    
    return changes

def process_file(file_path, all_field_stats):
    """处理单个YAML文件"""
    print(f"\n📝 处理文件: {os.path.basename(file_path)}")
    
    # 创建备份
    backup_path = f"{file_path}.backup-field-optimization"
    try:
        with open(file_path, 'r', encoding='utf-8') as src, open(backup_path, 'w', encoding='utf-8') as dst:
            dst.write(src.read())
    except Exception as e:
        print(f"❌ 无法创建备份: {e}")
        return False
    
    # 加载YAML数据
    data = load_yaml_file(file_path)
    if not data:
        return False
    
    total_changes = []
    
    # 处理每个实体
    if 'entities' in data:
        for entity_name, entity_def in data['entities'].items():
            print(f"  🔧 优化实体: {entity_name}")
            entity_changes = []
            
            # 优化字段定义
            field_changes = optimize_field_definitions({entity_name: entity_def}, all_field_stats)
            entity_changes.extend(field_changes)
            
            # 简化描述
            if 'attributes' in entity_def:
                desc_changes = simplify_descriptions(entity_def['attributes'])
                entity_changes.extend(desc_changes)
            
            total_changes.extend(entity_changes)
            
            # 打印实体的修改
            for change in entity_changes:
                print(change)
    
    # 保存修改后的文件
    if save_yaml_file(file_path, data):
        print(f"✅ {os.path.basename(file_path)} 优化完成")
        return True
    else:
        # 恢复备份
        try:
            with open(backup_path, 'r', encoding='utf-8') as src, open(file_path, 'w', encoding='utf-8') as dst:
                dst.write(src.read())
        except:
            pass
        return False

def main():
    if len(sys.argv) != 2:
        print("用法: python3 optimize-common-fields.py <models_directory>")
        sys.exit(1)
    
    models_dir = Path(sys.argv[1])
    if not models_dir.exists():
        print(f"❌ 目录不存在: {models_dir}")
        sys.exit(1)
    
    print("🚀 开始优化重复的字段定义...")
    print("=" * 50)
    
    # 查找所有YAML文件（排除备份文件）
    yaml_files = []
    for file_path in models_dir.glob("*.yml"):
        if not any(backup_suffix in file_path.name for backup_suffix in 
                  ['.backup', '.backup-phase1', '.backup-phase1-additional', 
                   '.backup-phase2', '.backup-field-optimization']):
            yaml_files.append(file_path)
    
    if not yaml_files:
        print("❌ 未找到YAML文件")
        sys.exit(1)
    
    # 第一步：分析所有文件中的字段使用情况
    print("📊 分析字段使用情况...")
    all_entities = {}
    
    for file_path in yaml_files:
        data = load_yaml_file(file_path)
        if data and 'entities' in data:
            all_entities[file_path.name] = data['entities']
    
    field_stats = analyze_common_fields(all_entities)
    
    # 显示通用字段统计
    print("\n📈 通用字段统计:")
    common_fields = ['id', 'createdAt', 'updatedAt']
    for field_name in common_fields:
        if field_name in field_stats:
            count = field_stats[field_name]['count']
            print(f"   - {field_name}: 出现在 {count} 个实体中")
    
    # 第二步：处理每个文件
    success_count = 0
    processed_files = []
    
    for file_path in sorted(yaml_files):
        if process_file(file_path, field_stats):
            success_count += 1
            processed_files.append(file_path.name)
    
    # 输出总结
    print("\n" + "=" * 50)
    print("📊 字段定义优化完成")
    print("=" * 50)
    print(f"✅ 成功处理: {success_count} 个文件")
    for file_name in processed_files:
        print(f"   - {file_name}")
    
    print(f"\n🔧 主要优化内容:")
    print(f"   - 🔧 标准化通用字段定义")
    print(f"   - 📝 简化冗余的description字段")
    print(f"   - 🎯 统一字段格式和规则")
    
    print(f"\n💾 备份文件已创建（.backup-field-optimization后缀）")
    print(f"📝 建议运行语法检查: npx tsx src/cli/syntax-check.ts models")
    print(f"🔄 如需恢复: find models -name '*.backup-field-optimization' -exec sh -c 'mv \"$1\" \"${{1%.backup-field-optimization}}\"' _ {{}} \\;")

if __name__ == "__main__":
    main()